package Tools;

import redis.clients.jedis.Jedis;

/**
 * @author zhang kun
 * @Classname RedisTool
 * @Description TODO
 * @Date 2021/8/2 21:37
 */
public class RedisTool {
    private static final String LOCK_SUCESS = "OK";
    private static final String SET_IF_NOT_EXIST = "NX";
    private static final String SET_WITH_EXPIRE_TIME = "PX";

    private static final Long RELEASE_SUCCESS = 1L;

    private static boolean tryGetDistricbuateLock(Jedis jedis,String lockKey,String requestID,int experTime){
        /**
         * 参数
         * 1.为当前加锁的key
         * 2.加锁的value,为了保证解锁的时候，由当前加锁的key,进行解锁
         * 3.NX：当key 存在不操作，不存在进行set
         * 4.PX,设置key过期
         * 5.为过期时间
         */
        String result = jedis.set(lockKey, requestID, SET_IF_NOT_EXIST, SET_WITH_EXPIRE_TIME, experTime);
        if(LOCK_SUCESS.equals(result)){
            return true;
        }
        return false;
    }

    /**
     *
     * @param jedis
     * @param locaKey
     * @param requestID
     * @return
     * 此方法调用了Lua 脚本，将参数KEYS[1] 赋值为localKey,ARGV[1] 赋值给requestId
     * Lua 脚本在执行的过程中，会被当成一个命令去执行，直到eval命令执行完成，Redis才会去执行别的命令。
     */
    public static boolean release(Jedis jedis,String locaKey,String requestID){
        String call = "if redis.call('get',KEYS[1] == ARGV[1] then return redis.call('del',KEYS[1) else return 0 end";
        Object result = jedis.eval(call);
        if(RELEASE_SUCCESS.equals(result)){
            return true;
        }
        return false;
    }

}
